package com.by.controller;

import com.by.service.RedisService;
import com.by.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
public class AuthController {

    private final JwtUtil jwtUtil;
    private final RedisService redisService;

    public AuthController(JwtUtil jwtUtil, RedisService redisService) {
        this.jwtUtil = jwtUtil;
        this.redisService = redisService;
    }

    /**
     * 模拟登录
     * 正常情况应该校验用户名 + 密码，这里为了演示，直接返回token
     */
    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestParam String username, @RequestParam String password) {
        // TODO: 实际项目里需要校验数据库里的用户名和密码
        if (!"admin".equals(username) || !"123456".equals(password)) {
            return ResponseEntity.status(401).body("Invalid username or password");
        }
        // 生成 token
        String accessToken = jwtUtil.generateAccessToken(username);
        String refreshToken = jwtUtil.generateRefreshToken(username);
        log.info("accessToken: {}", accessToken);
        log.info("refreshToken: {}", refreshToken);
        // refresh token 存入 Redis
        redisService.saveRefreshToken(refreshToken, username);

        Map<String, Object> response = new HashMap<>();
        response.put("accessToken", accessToken);
        response.put("refreshToken", refreshToken);

        return ResponseEntity.ok(response);
    }

    /**
     * 刷新 Access Token
     */
    @PostMapping("/refresh")
    public ResponseEntity<?> refresh(@RequestParam String refreshToken) {
        log.info("refresh>>>refreshToken: {}", refreshToken);
        // 1. 判断 refreshToken 是否在 Redis 中有效
        if (!redisService.isRefreshTokenValid(refreshToken)) {
            return ResponseEntity.status(401).body("Invalid refresh token");
        }

        // 2. 校验 refreshToken 是否过期
        if (!jwtUtil.validateToken(refreshToken)) {
            return ResponseEntity.status(401).body("Expired refresh token");
        }

        // 3. 获取用户ID
        String userId = jwtUtil.getUsernameFromToken(refreshToken);

        // 4. 生成新的 accessToken
        String newAccessToken = jwtUtil.generateAccessToken(userId);
        log.info("refresh>>>newAccessToken: {}", newAccessToken);
        Map<String, Object> response = new HashMap<>();
        response.put("accessToken", newAccessToken);

        return ResponseEntity.ok(response);
    }

    /**
     * 退出登录
     * 前端传 accessToken + refreshToken，后端拉黑 accessToken 并删除 refreshToken
     */
    @PostMapping("/logout")
    public ResponseEntity<?> logout(@RequestParam String accessToken,
                                    @RequestParam String refreshToken) {
        // 1. 将 accessToken 加入黑名单
        long expiration = jwtUtil.getExpiration(accessToken);
        if (expiration > 0) {
            redisService.addToBlacklist(accessToken, expiration);
        }

        // 2. 删除 refreshToken
        redisService.deleteRefreshToken(refreshToken);

        return ResponseEntity.ok("Logout success");
    }
    /**
     * 获取accessToken的剩余时间
     */
    @GetMapping("/accessToken/expiration")
    public ResponseEntity<?> getAccessTokenExpiration(@RequestParam String accessToken) {
        long expiration = jwtUtil.getExpiration(accessToken);
        if (expiration > 0) {
            return ResponseEntity.ok(expiration);
        } else {
            return ResponseEntity.status(401).body("Invalid access token");
        }
    }
    /**
     * 测试数据
     */
    @GetMapping("/test")
    public ResponseEntity<?> test() {
        return ResponseEntity.ok("test");
    }
}
